class User < ActiveRecord::Base

require 'digest/sha1'

  # unencrypted password
  attr_accessor :user_password

  #mass update protection
  attr_protected :admin

  # validation
  validates_length_of       :user_email, :within => 3..100
  validates_uniqueness_of   :user_email, :case_sensitive => false
  validates_presence_of     :user_name
  validates_length_of       :user_password, :within => 4..40,
                                       :if => :user_password_required? 
  
  validates_confirmation_of :user_password, :if => :user_password_required?
  
  # callbacks
  before_save :encrypt_password 

  # encrypts given password using salt
  def self.encrypt(pass, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{pass}--")
  end

 # authenticate by email/password 
  def self.authenticate(email, pass)
    user = find_by_user_email(email)
    user && user.authenticated?(pass) ? user : nil
  end

  # does the given password match the stored encrypted password
  def authenticated?(pass)
    encrypted_password == User.encrypt(pass, salt)
  end
  protected

  # before save - create salt, encrypt password
  def encrypt_password 
    return if user_password.blank?
    if new_record?
      self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{user_email}--")
    end
    self.encrypted_password = User.encrypt(user_password, salt)  
  end

  # no encrypted password yet OR password attribute is set
  def user_password_required?
    encrypted_password.blank? || !user_password.blank?
  end
end
